package com.yonyou.cyxdms.sysAuth.service.service.permission;

import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.sysAuth.service.constants.CommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.CommonTreeDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.CommonTreeStateDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.OrgPositionPO;
import com.yonyou.cyxdms.sysAuth.service.entity.role.RolePO;
import com.yonyou.cyxdms.sysAuth.service.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class PermissionServiceImpl implements PermissionService{

    // 定义日志接口
    private static final Logger logger = LoggerFactory.getLogger(PermissionServiceImpl.class);

    @Autowired
    UserOrgPositionMapper userOrgPositionMapper;

    @Autowired
    OrgPositionRoleMapper orgPositionRoleMapper;

    @Autowired
    PermissionMenuMapper permissionMenuMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    OrgPositionMapper orgPositionMapper;


    /**
     * 用户id去找到所对应的角色
     * @param userId
     * @return String
     */
    @Override
    public String queryRoleIds(Integer userId) {
       return userOrgPositionMapper.queryRoleIds(userId).get("roleIds").toString();
    }
    /**
     * 根据职位id去找到相对应的角色id
     *
     * @param
     * @return java.lang.String
     * @author dengqiang
     * @since 2019/7/25
     */
    @Override
    public String getRoleIds(String ids) {
        String result = "";


        List<String> idList = new ArrayList<>();
        if(ids != null){
            String[] idS = ids.split(",");
            for (String splId :idS){
                idList.add(splId);
            }
        }

       Map<String,Object> map = orgPositionRoleMapper.getRoleIds(idList);


        logger.debug(">>>>>>>>>>>>>>>>>map============================:{}",map);
        logger.debug(">>>>>>>>>>>>>>>>>!CommonUtils.isNullOrEmpty(map)============================:{}",!CommonUtils.isNullOrEmpty(map));
        logger.debug(">>>>>>>>>>>>>>>>>!StringUtils.isNullOrEmpty(map)============================:{}",!StringUtils.isNullOrEmpty(map));
        if (!CommonUtils.isNullOrEmpty(map)) {
            if (map.get(CommonConstants.ROLE_IDS) != null && !"".equals(map.get(CommonConstants.ROLE_IDS).toString().trim())) {
                result = map.get(CommonConstants.ROLE_IDS).toString().trim();
            }else {
                throw new ServiceBizException("选中职位未分配角色");
            }

        }
        return result;
    }

    @Override
    public List<CommonTreeDTO> queryPermissionMenu(String permission, Integer permissionType) {
        //获得产品类型
        Integer productType = null;
        Integer orgType = 0;
        Integer isFixed = isFixed();
        if(permissionType==ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE){
            RolePO role= roleMapper.selectById(permission);
            if(role!=null){
                orgType = role.getDataType();
            }
        }
        if(permissionType==ManageDictCodeConstants.BILL_TYPE_PERMISSION_POSITION){
            OrgPositionPO orgpositionpo = orgPositionMapper.selectById(permission);
            if(orgpositionpo != null){
                orgType = orgpositionpo.getDataType();
            }

        }

        //不固化的
        List<String> roleids = new ArrayList<>();
        if(permission != null){
            String[] ids = permission.split(",");
            for (String splId :ids){
                roleids.add(splId);
            }
        }
        List<Map<String,Object>> listmap = permissionMenuMapper.queryPermissionMenu2(orgType,productType,roleids,permissionType);

        return getOrgList(listmap, isFixed);
    }


    /**
     * 固化开关
     *
     * @return
     */
    public Integer isFixed() {

        Map<String, Object> map = permissionMenuMapper.isFixed();
        Integer isFixed = 0;
        if (!CommonUtils.isNullOrEmpty(map) && !StringUtils.isNullOrEmpty(map.get("IS_FIXED"))) {
            isFixed = (Integer) map.get("IS_FIXED");
        }
        return isFixed;
    }

    /**
     * @param listmap
     * @return java.util.List<com.yonyou.cyxdms.sysAuth.service.dto.CommonTreeDTO>
     * @author dengqiang
     * @since 2019/8/2
     */
    public List<CommonTreeDTO> getOrgList(List<Map<String, Object>> listmap, Integer isFixed) {
        Iterator<Map<String,Object>> it =  listmap.iterator();
        List<CommonTreeDTO> orgList = new ArrayList<>();
        while (it.hasNext()) {
            CommonTreeDTO orgTreeOrg = new CommonTreeDTO();
            CommonTreeStateDTO commonTreeStateDto = new CommonTreeStateDTO();
            Map<String,Object> menuMap = it.next();
            orgTreeOrg.setId(menuMap.get("MENU_ID").toString());
            String parent = menuMap.get("PARENT_ID").toString();
            if ("0".equals(parent)) {
                parent = "#";
            }

            commonTreeStateDto.setChecked(StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, menuMap.get("IS_EMPOWERED").toString()));

            if (!StringUtils.isNullOrEmpty(menuMap.get(CommonConstants.IS_FLEXIBLE)) && !StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, menuMap.get(CommonConstants.IS_FLEXIBLE).toString()) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, isFixed.toString())) {
                commonTreeStateDto.setCheckboxDisabled(true);
            }
            if (!StringUtils.isNullOrEmpty(menuMap.get(CommonConstants.IS_FLEXIBLE)) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, menuMap.get(CommonConstants.IS_FLEXIBLE).toString()) && StringUtils.isEquals(ManageDictCodeConstants.STATUS_IS_YES, isFixed.toString())) {
                menuMap.put(CommonConstants.MENU_NAME, menuMap.get(CommonConstants.MENU_NAME).toString() + "[可分配]");
            }
            orgTreeOrg.setParent(parent);
            String menuName = menuMap.get("MENU_NAME").toString();
            orgTreeOrg.setText(menuName);
            orgTreeOrg.setState(commonTreeStateDto);
            orgList.add(orgTreeOrg);
        }
        return orgList;
    }


}
